
<template>
  <!-- 实况监测-气候背景 -->
  <div class="climateBgConain">
    <nut-overlay v-model:visible="modalshow" 
    :overlay-style="{
      backgroundColor: 'rgba(0, 0, 0, .2)'
    }" :close-on-click-overlay="false">
    </nut-overlay>
    <div class="climateContainTabContainer">
      <div class="climateContainTab">
        <span v-for="item in tabData" :key="item.id" :class="[activeTabData.id == item.id?'active':'']" @click.native="tabClick(item)">{{item.label}}</span>
      </div>
    </div>
    
    <div class="climateContainHoursContain">
     <div class="climateContainHours">
        <span v-for="item in elementsData" :key="item.id" :class="[activeElement == item.id?'active':'']"  @click.native="elementClick(item)">{{item.label}}</span>
     </div>
     <div class="climateContainTime">
      <div :class="['climateContainTimeSingle',activeTabData.id]">
        <span class="calendar"></span>
        <nut-cell title="" :desc="desc"  @click="show = true"></nut-cell>
        <nut-datepicker v-if="activeTabData.id =='month'" v-model="currentDate" title="月评估"  type="year-month" @confirm="confirmMonth"  v-model:visible="show" ></nut-datepicker>
        <nut-datepicker v-else-if="activeTabData.id =='year'" v-model="currentDate" title="年评估"  type="year-month" @confirm="confirmYear"  v-model:visible="show" :filter="filter"></nut-datepicker>  
        <!-- <nut-cascader   v-else v-model="currentDate"  title="选择季"  :options="reasonData"  v-model:visible="show" ></nut-cascader> -->
        <nut-popup v-else v-model:visible="show" position="bottom">
          <nut-picker v-model="currentDate" :columns="reasonData" title="季评估" @confirm="confirmReason" @cancel="show = false" v-model:visible="show" />
        </nut-popup>
      </div>
      <div class="climateContainTimeSingleBtn" v-if="activeTabData.id =='month'">
        <div @click="monthClick(-1)">上一月</div>
        <div @click="monthClick(1)">下一月</div>
      </div>
      <div class="climateContainTimeSingleBtn" v-else-if="activeTabData.id =='reason'">
        <div @click="reasonClick(-1)">上一季</div>
        <div @click="reasonClick(1)">下一季</div>
      </div>
      <div class="climateContainTimeSingleBtn" v-else>
        <div @click="yearClick(-1)">上一年</div>
        <div @click="yearClick(1)">下一年</div>
      </div>
     </div>
    </div>
    <div class="climateTitle" ><div class="title1">{{projectConfig.cityName}}各站{{activeElement == 'RAIN'?'累计雨量':'平均温度'}}评估</div></div>
    <div class="imgContain">
      <div ref="echartContain" style="height: 400px"></div>
    </div>
    <div class="climateTitle"><div class="title2">{{activeElement == 'RAIN'?'累计降水量':'平均温度'}}统计</div>
    </div>
    <div class="tableContain">
      <nut-table :columns="tablecolumns" :data="tableData"></nut-table>
    </div>
    <nut-backtop @click="handleClick" ></nut-backtop>
  </div>
</template>

<script setup lang="ts">
import { climateES } from '@/api/skMountiorApi'
import projectConfig from "@/config/projectConf.js";
import * as echarts from 'echarts'
import moment from "moment";
//遮罩显示
const modalshow = ref(false);

//tab切换数据
const tabData = ref([
  {id:'month','label':'月评估',timeType:3,tableColumnText:'月'},
  {id:'reason','label':'季评估',timeType:4,tableColumnText:'季'},
  {id:'year','label':'年评估',timeType:5,tableColumnText:'年'},
])
const activeTabData = ref(tabData.value[0]);
const tabClick = (item:any)=>{
  if(activeTabData.value.id != item.id){
    activeTabData.value = item;
    if(item.id == "month"){
      desc.value = moment().format("YYYY年MM月")
      currentDate = new Date(moment().subtract(1,'months').format("YYYY-MM"));
    }else if(item.id == "year"){
      desc.value = moment().format("YYYY年")
      currentDate = new Date(moment().format("YYYY"));
    }else{
      const startYear =  - 5;
      const endYear =  5;
      let data = [];
      for(let i = startYear;i<=endYear;i++){
        data.push({
          text:`${moment().add(i-1, 'Y').format('YYYY年12月')} - ${moment().add(i, 'Y').format("YYYY年02月")}`,
          value:`${moment().add(i-1, 'Y').format('YYYY年12月')} - ${moment().add(i, 'Y').format("YYYY年02月")}`,
          interfaceTime:`${moment().add(i, 'Y').format("YYYY-04")}`,
        });
        data.push({
          text:`${moment().add(i, 'Y').format('YYYY年03月')} - ${moment().add(i, 'Y').format("YYYY年05月")}`,
          value:`${moment().add(i, 'Y').format('YYYY年03月')} - ${moment().add(i, 'Y').format("YYYY年05月")}`,
          interfaceTime:`${moment().add(i, 'Y').format("YYYY-01")}`,
        });
        data.push({
          text:`${moment().add(i, 'Y').format('YYYY年06月')} - ${moment().add(i, 'Y').format("YYYY年08月")}`,
          value:`${moment().add(i, 'Y').format('YYYY年06月')} - ${moment().add(i, 'Y').format("YYYY年08月")}`,
          interfaceTime:`${moment().add(i, 'Y').format("YYYY-02")}`,
        });
        data.push({
          text:`${moment().add(i, 'Y').format('YYYY年09月')} - ${moment().add(i, 'Y').format("YYYY年11月")}`,
          value:`${moment().add(i, 'Y').format('YYYY年09月')} - ${moment().add(i, 'Y').format("YYYY年11月")}`,
          interfaceTime:`${moment().add(i, 'Y').format("YYYY-03")}`,
        });
      }
      reasonData.value = data;
      let value = "";
      if(Number(moment().month())>=9){
        value = `${moment().format('YYYY年09月')} - ${moment().format("YYYY年11月")}`
      }else if(Number(moment().month())>=6){
        value = `${moment().format('YYYY年06月')} - ${moment().format("YYYY年08月")}`
      }else if(Number(moment().month())>=3){
        value = `${moment().format('YYYY年03月')} - ${moment().format("YYYY年05月")}`
      }else{
        value = `${moment().add(-1, 'Y').format('YYYY年12月')} - ${moment().format("YYYY年02月")}`
      }
      desc.value = value;
      currentDate = value;
    }
    getData();
  }
}

//要素数据
const activeElement = ref("RAIN");
const elementsData = ref([
  {id:'RAIN','label':'降水量',orderBy: 'desc',unit:'(mm)'},
  {id:'TAVG','label':'温度',orderBy: 'desc',unit:'(℃)'}
])
const elementClick = (item:any)=>{
  if(activeElement.value != item.id){
    activeElement.value = item.id;
    getData();
  }
}


//设置日期
// let time  = moment().format("YYYY-MM-DD HH:00:00");
const show = ref(false);
const desc = ref(moment().subtract(1,'months').format("YYYY年MM月"));
let currentDate = new Date(moment().subtract(1,'months').year(),moment().subtract(1,'months').month());
// currentDate.value = time;
const confirmMonth = ( { selectedValue, selectedOptions } )=>{
 const date = selectedValue.slice(0, 3).join('-');
 const time = selectedValue.slice(3).join(':');
 desc.value = moment(date + ' ' + time).format("YYYY年MM月");
 getData();
}
const confirmYear = ( { selectedValue, selectedOptions } )=>{
 const date = selectedValue.slice(0, 3).join('-');
 const time = selectedValue.slice(3).join(':');
 desc.value = moment(date + ' ' + time).format("YYYY年");
 getData();
}
const confirmReason = ({ selectedValue, selectedOptions })=>{
  currentDate = selectedValue[0];
  desc.value =selectedValue[0];
  console.log(selectedValue[0], selectedOptions[0])
  getData();
}

const monthClick = (time:any)=>{
  let newTime = moment(currentDate).add('months',time);
  currentDate = new Date(moment(newTime).format("YYYY-MM"));
  desc.value = moment(newTime).format("YYYY年MM月");
  getData();
}
const yearClick = (time:any)=>{
  let newTime = moment(currentDate).add('years',time);
  currentDate = new Date(moment(newTime).format("YYYY"));
  desc.value = moment(newTime).format("YYYY年");
  getData();
}

const reasonClick = (time:any)=>{
  let index = reasonData.value.findIndex(item=>item.value == desc.value);
  let newIndex =  index+time;
  if(newIndex>reasonData.value.length-1){
    newIndex = 0;
  }
  if(newIndex<0){
    newIndex = reasonData.value.length-1;
  }
  currentDate = reasonData.value[newIndex].value;
  desc.value = reasonData.value[newIndex].value;
  getData();
}

//季数据
let reasonData = ref([
  { text: '2012年12月-2013年02月', value: '2012年12月-2013年02月' },
  { text: '2013年03月-2013年05月', value: '2013年03月-2013年05月' },
  { text: '2013年06月-2013年08月', value: '2013年06月-2013年08月' },
  { text: '2013年09月-2013年11月', value: '2013年09月-2013年11月' },
  { text: '2013年12月-2014年02月', value: '2013年12月-2014年02月' },
  { text: '2014年05月-2014年08月', value: '2014年05月-2014年08月' },
  { text: '2014年09月-2014年11月', value: '2014年09月-2014年11月' }
])
const filter = (type, options) => {
  if (type === 'month') {
    return []
  }
  return options
}




const tableData = ref([]);
let tablecolumns = [];
//查询数据
const getData =()=>{
  debugger
  modalshow.value = true;
  let time = desc.value.replace('年',"")
  if(activeTabData.value.id == "month"){
    time = desc.value.replace('年',"-").replace('月',"");
  }
  if(activeTabData.value.id == "reason"){
    let index = reasonData.value.findIndex(item=>item.value == desc.value);
    if(index == -1){
      index = 0;
    }
    time = reasonData.value[index].interfaceTime;
  }
  tablecolumns = [
    { title: '站名', key: 'name',align: 'center' },
    { title: '本'+activeTabData.value.tableColumnText+(activeElement.value == 'RAIN'?'降水量':'平均气温'), key: 'val',align: 'center'},
    { title: '历史同期排名', key: 'synchNum',align: 'center'}
  ]
  if(activeElement.value == "RAIN"){
    tablecolumns.push({ title: '历史同期最多', key: 'synchMax',align: 'center'});
  }else{
    tablecolumns.push({ title: '历史同期最高', key: 'synchMax',align: 'center'});
    tablecolumns.push({ title: '历史同期最低', key: 'synchMin',align: 'center'});
  }
  climateES(activeElement.value, activeTabData.value.timeType, time,time).then((res:any) => {
    modalshow.value = false;
    if (res.code === 200) {
      res.data.map(item=>{
        if(item.synchMin && item.synchMin !="" && item.synchMin_year && item.synchMin_year!=""){
          item.synchMin = item.synchMin+"("+item.synchMin_year+")";
        }
        if(item.synchMax && item.synchMax !="" && item.synchMax_year && item.synchMax_year!=""){
          item.synchMax = item.synchMax+"("+item.synchMax_year+")";
        }
      })
      tableData.value = res.data;
      createBarChart({
        yAxisName: activeElement.value == 'RAIN'?'累计雨量(mm)':'平均温度(℃)',
        data: res.data
      })
    }else{
      tableData.value = [];
      createBarChart({
        yAxisName: activeElement.value == 'RAIN'?'累计雨量(mm)':'平均温度(℃)',
        data: []
      })
    }
  })
}
 /**
 * 创建条形图
 * @param yAxisName y坐标的名称
 * @param series 图表的数据
 */
const echartContain = ref()
let chartObj = null;
const createBarChart = ({ yAxisName, data })=> {
  chartObj = echarts.init(echartContain.value);
  let category = [];
  let series1 = [];
  let series2 = [];
  data.map(item=>{
    category.push(item.name);
    series1.push(item.val);
    series2.push(item.cimateVal);
  })

  const option = {
    legend: {
      type: 'plain',
      right: 0,
    },
    grid: {
      top: '30',
      left: '10',
      right: '10',
      bottom: '10',
      containLabel: true,
      show: true,
      borderWidth: 2,
      borderColor: '#000'
    },
    color: [
      {
        type: 'linear',
        x: 0,
        y: 0,
        x2: 0,
        y2: 1,
        colorStops: [{
            offset: 1, color: '#ec8820' // 0% 处的颜色
        }, {
            offset: 0, color: '#f4b14a' // 100% 处的颜色
        }],
        global: false // 缺省为 false
      },
      {
        type: 'linear',
        x: 0,
        y: 0,
        x2: 0,
        y2: 1,
        colorStops: [{
            offset: 1, color: '#3b76ff' // 0% 处的颜色
        }, {
            offset: 0, color: '#6ea5ff' // 100% 处的颜色
        }],
        global: false // 缺省为 false
      }
    ],
    xAxis: {
      type: 'category',
      data: category,
      splitLine: {
        show: true,
        lineStyle: {
          color: '#b9c2d8',
          type: 'dashed'
        },
        interval: (index) => {
          return index > 0
        }
      },
      splitArea: {
        show: true,
        interval: 0,
        areaStyle: {
          color: ['#f3f4f5', '#ffffff'],
        },
      },
      axisLabel: {
        fontSize: 14,
        color: '#313133',
      },
      axisTick: {
        show: false
      },
      axisLine: {
        show: false
      },
    },
    yAxis: {
      name: yAxisName,
      nameTextStyle: {
        color:'#666666',
        fontSize: 14,
        align: 'left'
      },
      nameGap: 10,
      type: 'value',
      splitLine: {
        show: false
      },
      axisLabel: {
        fontSize: 14,
        color: '#313133'
      },
      axisLine: {
        show: false
      },
      axisTick: {
        show: true,
      }
    },
    series: [
      {
        name: '实况',
        data: series1,
        type: 'bar',
        barWidth: 20,
        itemStyle:{
          normal:{
            label:{
              show:true,
              position:'top',
              textStyle:{
                fontWeight:'bolder'
              }
            }
          }
        }
      },
      {
        name: '常年值',
        data: series2,
        type: 'bar',
        barWidth: 20,
        itemStyle:{
          normal:{
            label:{
              show:true,
              position:'top',
              textStyle:{
                fontWeight:'bolder'
              }
            }
          }
        }
      }
    ]
  }
  chartObj.setOption(option)
}
//回到顶部
const handleClick = () => {
  console.log('触发返回顶部');
};

onMounted(() => {
  getData();
});

onUnmounted(() => {
});
</script>
<style lang="scss">
.climateContainTime{
  position: relative;
  .nut-cell{
    background: transparent !important;
    box-shadow: none;
    margin: 0px;
    padding:0px;
    .nut-cell__value--alone{
      color:#fff;
      line-height: 25px;
      padding-right: 2px;
      padding-left: 25px;
      font-size: 13px;
      text-align: center!important;
    }
  }
  // .climateContainTimeSingle{
  //   // .nut-icon{
  //   //   position: absolute;
  //   //   top: 7px;
  //   //   left: 5px;
  //   // }
  // }
}
.climateBgConain{
  .nut-table__main__head__tr--border{
    border: none;
  }
  .nut-table__main__body{
    color: #000;
    background: #fff;
  }
  .nut-table__main__head{
    color: #fff;
    background: #4f80fa;
  }
  .nut-table__main__body__tr__td{
    padding:5px 0px;
  }
  .nut-backtop.show{
    width: 40px;
    height: 40px;
    right:25px !important;
  }
  .firstIcon{
    width: 100%;
    height: 15px;
    background: url('@/assets/images/icon_no1.png') center center no-repeat;
  }
  .secondIcon{
    width: 100%;
    height: 15px;
    background: url('@/assets/images/icon_no2.png') center center no-repeat;
  }
  .thirdIcon{
    width: 100%;
    height: 15px;
    background: url('@/assets/images/icon_no3.png') center center no-repeat;
  }
}
</style>
<style scoped lang="scss">
.climateBgConain{
  width: 100%;
  min-height: 200px;
  color:#d5d5d5;
  font-size: 16px;
  // padding-bottom: 30px;
  .climateContainTabContainer{
    width: 100%;
    height: 50px;
    align-items: flex-end;
    display: flex;
    background: url('@/assets/images/bg.png') right bottom no-repeat #4574eb;
    .climateContainTab{
      width: 100%;
      height: 30px;
      line-height: 30px;
      display: flex;
      margin: 0px 10px;
      >span{
        flex: 1;
        text-align: center;
        &.active{
          font-weight: bold;
          color:#fff;
          border-bottom:2px solid #fff;
        }
      }
    }
  }
 
 
  .climateContainHours{
    height: 35px;
    line-height: 35px;
    display: flex;
    >span{
      //flex: 1;
      width: 30%;
      text-align: center;
      &.active{
        font-weight: bold;
        color:#fff;
        border-bottom:2px solid #fff;
      }
    }
  }
  .climateContainHoursContain{
    background: #2c50ae;
    .climateContainHours{
      margin: 0px 10px;
      margin-bottom: 5px;
    }
    .climateContainTime{
      margin: 0px 10px;
      display: flex;
      height: 30px;
      line-height: 30px;
      .climateContainTimeSingle{
        width: 160px;
        border:1px solid #fff;
        border-radius: 3px;
        display:flex;
        height: 25px;
        margin-right: 5px;
        &.reason{
          width: 200px;
        }
        .calendar{
          height: 23px;
          width: 25px;
          position: absolute;
          top: 1px;
          left: 6px;
          background: url('@/assets/images/calendar.png') center center no-repeat;
        }
      }
      .climateContainTimeSingleRefresh{
        position: relative;
        width: 36px;
        text-align: center;
        .switch{
          display: inline-block;
          width: 36px;
          height: 29px;
          background: url('@/assets/images/Switch.png') center center no-repeat;
        }
      }
      .climateContainTimeSingleBtn{
        flex: 1;
        display: flex;
        color: #fff;
        line-height: 25px;
        height: 25px;
        div{
          // flex: 1;
          margin-right: 5px;
          border:1px solid #fff;
          border-radius: 3px;
          font-size: 13px;
          background-repeat: no-repeat;
          text-align: center;
          background-size: 13px 13px;
          padding:0px 10px;
        }
      }
    }
  }
  .climateTitle{
    width: 100%;
    text-align: center;
    height: 50px;
    line-height: 70px;
    background: #fff;
    margin-top: 10px;
    margin-bottom: 10px;
    color: #000;
    justify-content: center;
    display: flex;
    >div{
      width: 320px;
      font-weight: bold;
      &.title1{
        background-image: url("@/assets/images/titleBg1.png");
        background-repeat: no-repeat;
        background-position: center center;
        background-size: contain;
      }
      &.title2{
        background-image: url("@/assets/images/titleBg2.png");
        background-repeat: no-repeat;
        background-position: center center;
        background-size: contain;
      }
      position: relative;
    }
  }
  .tableContain,.imgContain{
    padding:0px 10px;
  }
}
</style>
